import {Http, Headers, RequestOptions, RequestOptionsArgs} from '@angular/http';
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/throw';
import { LoginService } from './login.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpService {
    constructor(
        private http: HttpClient,
        private loginService: LoginService,
    ) {
    }
    // http header
    // headers = new Headers({
    //     'Content-Type': 'application/x-www-form-urlencoded',
    //     // 'token': this.userServiceProvider.user ? this.userServiceProvider.user.token : '',
    // });
    // options = new RequestOptions({headers: this.headers});
    // get请求
    get(url: string, option?): Observable<any> {
        const headers = new HttpHeaders().set('Authorization', 'Bearer ' + this.loginService.user.token);
        if (option) {
            url = url + '?';
            for (const key in option) {
                if (option.hasOwnProperty(key)) {
                    const element = option[key];
                    url += key + '=' + element + '&';
                }
            }
            url = url.replace(/\&$/g, i => '');
        }
        return this.http.get(url, {headers})
            // .map(res => res.json());
    }

    // post请求
    post(url: string, body: any): Observable<any> {
        const headers = new HttpHeaders()
        .set('Authorization', this.loginService.user ? 'Bearer ' + this.loginService.user.token : '');
        return this.http.post(url, body, {headers})
            // .map(res => res.json());
    }
}